package development.game;

import java.util.Random;

import state.DrawListener;
import state.GameAlert;
import state.GameConstants;
import state.GameControl;
import state.GameForm;
import state.GameGlobal;
import state.GameImage;
import state.Graphics;
import state.Key;
import state.Sprite;
import state.TimerListener;
import state.font.FontManager;
import state.font.ImageText;
import state.socket.DataPackage;
import state.socket.DataReceiveListener;
import state.util.GameColor;
import state.util.GameStringUtils;
import state.util.Hashtable;
import state.util.ImageUtil;
import state.util.NumberUtil;
import state.util.array.StringArray;
import development.Constants;
import development.DrawUtils;
import development.Global;
import development.bean.Game;
import development.bean.User;
import development.group.FrmGroupListTableFreeUserChat;
import development.group.FrmGroupTableFreeUserFriend;
import development.socket.SocketClientUtil;

public class FrmDaoVang extends GameForm implements DataReceiveListener, TimerListener {
  private final int SELECT_TO_PULL = 5001;
  private final int ROB_OBJECT = 6001;
  private final int START_TO_PLAY_RESPONSE = 4001;
  private final int SELECTED_ITEM = 7001;
  private final int SUCCESS_PULL = 5555;
  private final int BUY_ITEM = 6666;
  private final int END_GAME = 1222;
  private final int OPPONENT_RESIGN_WIN_REASON = 4002;
  private final int WIN_GAME_NOTIFY_RESPONSE = 2006;
  private final int EQUAL_GAME_RESULT = 4444;
  private final int NORMAL_WIN_REASON = 7777;
  private final int TIME_OUT_PER_QUESTION_SIGNAL = 3007;
  private boolean isTangLuc1 = false;
  private boolean isTangLuc2 = false;
  private boolean isRobber1 = false;
  private boolean isRobber2 = false;
  private Sprite groundSprite;
  private Sprite ngamSprite;
  private Sprite ngamSprite1;
  private Sprite personSprite;
  private Sprite personSprite1;
  private Sprite[] objectSprite;
  private GameImage[] personImage;
  private GameImage[] ngamImages;
  private GameImage ngamImage;
  private GameImage[] objectImages;
  private GameImage personLargeImg;
  private GameImage bgImage;
  private int[] ObjX;
  private int[] ObjY;
  private int[] xLine0;
  private int[] xLine1;
  private int[] yLine;
  private float X;
  private int Y;
  private float XX;
  private int YY;
  private String[] nameObject;
  private int step;
  private int indexToado1;
  private int indexToado2;
  private int selectIndex1;
  private int selectIndex2;
  private boolean isDrawLine11;
  private boolean isDrawLine12;
  private boolean isDrawLine21;
  private boolean isDrawLine22;
  private String[] randString2;
  private int speed1;
  private int speed2;
  private int countObject;
  private int k1;
  private int k2;
  private int dx1;
  private int dx2;
  private int time;
  private Random rd;
  private GameImage bosoImg;
  private GameImage[] bosoImage;
  private String scoreStr1;
  private String scoreStr2;
  private String timeStr;
  private int count;
  private int curentscore2;
  private int curentscore1;
  private int[] dxMouse;
  private boolean isTNT1;
  private boolean isTNT2;
  private GameImage[] noImgs;
  private int Y00;
  private int X00;
  private int X01;
  private int Y01;
  private GameImage bucdungImg;
  private int[] ext;
  private int[] extY;
  public float[] TRIANGLE;
  private float[] cosin;
  private boolean isEndgame;
  private boolean[] isPulling1;
  private boolean[] isPulling2;
  private GameImage diem1Image;
  private GameImage diem2Image;
  private ImageText text8;

  private int winSide;
  private String[] moneyChangePoint = new String[2];
  boolean isShowWinOrLostAlert;
  boolean isShowResult;

  private GameImage matnaImage;
  private GameImage randManaImage;
  private GameImage starImage;
  private GameImage thangImage;
  private GameImage thuaImage;
  private GameImage boughtItem1;
  private GameImage boughtItem2;
  private boolean isShowItemBoard;
  private GameImage boardItemImg;
  private boolean isfinishInit;
  private int DX;
  private int level;
  private Sprite resultSprite;
  private GameImage clockImage;
  private GameImage hoaImage;
  private boolean isHoa;
  private Sprite boardSprite;
  private String oponentName;
  private int myLevel;
  private int oppLevel;
  // private Image continueImage;
  private GameImage closeImage;
  boolean sent;
  private boolean isEndGame;
  private int SCREEN_WIDTH = 240;
  private int SCREEN_HEIGH = 320;
  private static GameForm singleton;

  public static GameForm instance() {
    if (singleton == null) {
      singleton = new FrmDaoVang();
    }
    return singleton;
  }

  public void init(Hashtable parameters) {
    DrawUtils.setBottomBar(_manager, "", "", "");
    isEndGame = false;
    _manager.enableTouchPad();
    if (Constants.IS_240x320_SCREEN) {
      bgImage = ImageUtil.getImage(Constants.DAO_VANG_IMAGE_CATEGORY, "bg_play.png");
    } else {
      bgImage = ImageUtil.getImage(Constants.DAO_VANG_IMAGE_CATEGORY, "bg_play_320.png");
    }
    
    new GameControl() {
      public void perform() {
        Global.alert.showAlert(FrmDaoVang.instance(), GameAlert.LOADING_WITH_NO_BUTTON_TYPE, "Đang bắt đầu game...");
      }
    }.setTimeInterval(500).start();
  }
  
  public void initForGame(DataPackage dataPackage) {
    isfinishInit = false;
    if (Constants.IS_240x320_SCREEN) {
      int[] a = new int[] { 144, 145, 146, 146, 148, 149, 150, 151, 152, 153, 155, 157, 158, 159, 161, 163, 164, 165, 167, 168, 169, 170, 171, 172, 173, 173, 174 };
      int[] b = new int[] { 64, 65, 66, 66, 68, 69, 70, 71, 72, 73, 75, 77, 78, 79, 81, 83, 84, 85, 87, 88, 89, 90, 91, 92, 93, 93, 94 };

      X00 = 160;// 180 chu phong ben tay phai
      Y00 = 92;
      X01 = 80; // khach ben tay trai
      Y01 = 92;
      xLine0 = a;
      xLine1 = b;
    } else {
      int[] a = new int[] { 184, 185, 186, 186, 188, 189, 190, 191, 192, 193, 195, 197, 198, 199, 201, 203, 204, 205, 207, 208, 209, 210, 211, 212, 213, 213, 214 };
      int[] b = new int[] { 104, 105, 106, 106, 108, 109, 110, 111, 112, 113, 115, 117, 118, 119, 121, 123, 124, 125, 127, 128, 129, 130, 131, 132, 133, 133, 134 };
      X00 = 200;// chu phong ben tay phai
      Y00 = 52;// 92 tren ban doc
      X01 = 120; // khach ben tay trai//80
      Y01 = 52;
      xLine0 = a;
      xLine1 = b;
    }
    
    if (Constants.IS_240x320_SCREEN) {
      SCREEN_WIDTH = 240;
      SCREEN_HEIGH = 320;
    } else {
      SCREEN_WIDTH = 320;
      SCREEN_HEIGH = 240;
    }

    isShowResult = false;
    isShowWinOrLostAlert = false;
    ext = new int[] { -7, -6, -5, -4, -3, -3, -3, -2, -2, -2, -2, -1, -1, 0, 0, 0, 1, 1, 2, 2, 2, 2, 3, 3, 4, 5, 6, 7 };
    extY = new int[] { -4, -4, -3, -3, -3, -3, -2, -2, -2, -2, -2, -1, -1, 0, 0, 0, -1, -1, -2, -2, -2, -2, -3, -3, -3, -3, -4, -4 };
    TRIANGLE = new float[] { 3.732050807568877f, 2.747477419454622f, 2.144506920509559f, 1.732050807568877f, 1.428148006742114f, 1.19175359259421f, 1.0f, 0.83909963117728f, 0.7002075382097098f,
        0.5773502691896257f, 0.4663076581549986f, 0.3639702342662023f, 0.267949192431123f, 0.176326980708465f };
    cosin = new float[] { 0.2588190451025207f, 0.3420201433256687f, 0.4226182617406994f, 0.5f, 0.5735764363510461f, 0.6427876096865394f, 0.7071067811865476f, 0.766044443118978f, 0.819152044288992f,
        0.866025403784439f, 0.9063077870366499f, 0.9396926207859084f, 0.9659258262890683f, 0.984807753012208f };
    isEndgame = false;
    curentscore1 = 0;
    curentscore2 = 0;
    count = 0;
    indexToado1 = 0;
    indexToado2 = 0;
    step = 0;
    speed1 = 0;
    speed2 = 0;
    k1 = 0;
    k2 = 0;
    dx1 = 1;
    dx2 = 1;
    time = 45;
    isTangLuc1 = false;
    isTangLuc2 = false;
    isRobber1 = false;
    isRobber2 = false;
    sent = false;
    X = -1;
    Y = -1;
    XX = -1;
    YY = -1;
    selectIndex1 = -1;
    selectIndex2 = -1;
    isDrawLine11 = false;
    isDrawLine12 = false;
    isDrawLine21 = false;
    isDrawLine22 = false;
    isTNT1 = false;
    isTNT2 = false;
    isEndgame = false;
    winSide = -1;
    isShowItemBoard = false;
    isHoa = false;
    DX = 0;
    if (!Constants.IS_240x320_SCREEN) {
      DX = 40;
    }
    text8 = FontManager.getFont(FontManager.FONT_SIZE_8);
    randString2 = new String[] { "25", "105", "206", "270", "350", "435", "520", "715", "800", "950" };
    if (Constants.IS_240x320_SCREEN) {
      yLine = new int[] { 95, 98, 100, 102, 104, 105, 106, 107, 108, 109, 110, 110, 110, 110, 110, 110, 109, 108, 107, 106, 105, 104, 102, 100, 98, 97, 95 };
    } else {
      yLine = new int[] { 55, 58, 60, 62, 64, 65, 66, 67, 68, 69, 70, 70, 70, 70, 70, 70, 69, 68, 67, 66, 65, 64, 62, 60, 58, 57, 55 };
    }

    rd = new Random();
    countObject = getCountObject("/DaoVang/level" + (level + 1) + ".txt");
    ObjX = new int[countObject];
    ObjY = new int[countObject];
    bosoImage = new GameImage[11];
    ngamImages = new GameImage[27];

    ngamImage = ImageUtil.getImage(Constants.DAO_VANG_IMAGE_CATEGORY, "ngam.png");
    for (int i = 0; i < 27; i++) {
      ngamImages[i] = ImageUtil.rotate(ngamImage, 360 - 5 * i);
    }
    bucdungImg = ImageUtil.getImage(Constants.DAO_VANG_IMAGE_CATEGORY, "bucdung.png");
    GameImage noImg = ImageUtil.getImage(Constants.DAO_VANG_IMAGE_CATEGORY, "no.png");
    noImgs = new GameImage[7];
    for (int i = 0; i < 7; i++) {
      noImgs[i] = ImageUtil.getSubImage(noImg, i * 41, 0, 41, 41, true);
    }
    noImg = null;
    bosoImg = ImageUtil.getImage(Constants.DAO_VANG_IMAGE_CATEGORY, "boso.png");
    for (int i = 0; i < 11; i++) {
      bosoImage[i] = ImageUtil.getSubImage(bosoImg, 9 * i, 0, 8, 12, true);
    }
    bosoImg = null;
    personImage = new GameImage[5];
    personLargeImg = ImageUtil.getImage(Constants.DAO_VANG_IMAGE_CATEGORY, "person.png");
    for (int i = 0; i < 5; i++) {
      personImage[i] = ImageUtil.getSubImage(personLargeImg, i * 44, 0, 44, 44, true);
    }
    personLargeImg = null;
    nameObject = readMapText("/DaoVang/level" + (level + 1) + ".txt", ObjX, ObjY);
    objectImages = new GameImage[countObject];
    for (int i = 0; i < countObject; i++) {
      objectImages[i] = ImageUtil.getImage(Constants.DAO_VANG_IMAGE_CATEGORY, nameObject[i] + ".png");
    }
    diem1Image = ImageUtil.getImage(Constants.DAO_VANG_IMAGE_CATEGORY, "diem1.png");
    diem2Image = ImageUtil.getImage(Constants.DAO_VANG_IMAGE_CATEGORY, "diem2.png");
    clockImage = ImageUtil.getImage(Constants.DAO_VANG_IMAGE_CATEGORY, "icon_clock.png");
    randManaImage = ImageUtil.getImage(Constants.HIEU_UNG_IMAGE_CATEGORY, "pxiel_nen.png");
    matnaImage = ImageUtil.joinAndCreateImages(randManaImage, SCREEN_WIDTH, SCREEN_HEIGH - 20);
    thuaImage = ImageUtil.getImage(Constants.HIEU_UNG_IMAGE_CATEGORY, "icon_lose.png");
    thangImage = ImageUtil.getImage(Constants.HIEU_UNG_IMAGE_CATEGORY, "icon_win.png");
    hoaImage = ImageUtil.getImage(Constants.HIEU_UNG_IMAGE_CATEGORY, "icon_hoa.png");
    starImage = ImageUtil.getImage(Constants.HIEU_UNG_IMAGE_CATEGORY, "HieuUng.png");
    boardItemImg = ImageUtil.getImage(Constants.DAO_VANG_IMAGE_CATEGORY, "board_items.png");
    boughtItem1 = ImageUtil.getImage(Constants.DAO_VANG_IMAGE_CATEGORY, "icon_suc_manh.png");
    boughtItem2 = ImageUtil.getImage(Constants.DAO_VANG_IMAGE_CATEGORY, "icon_cuop_vang.png");
    // continueImage = ImageUtil.getImage(Constants.DAO_VANG_IMAGE_CATEGORY, "choi_tiep.png");
    closeImage = ImageUtil.getImage(Constants.DAO_VANG_IMAGE_CATEGORY, "close_shop.png");
    dxMouse = new int[countObject];
    isPulling1 = new boolean[countObject];
    isPulling2 = new boolean[countObject];
    for (int i = 0; i < countObject; i++) {
      dxMouse[i] = -3;
      isPulling1[i] = false;
      isPulling2[i] = false;
    }

    objectSprite = new Sprite[countObject];
    groundSprite = new Sprite(null, _manager, 0, 0, Constants.TOP_LEFT_ANCHOR);
    groundSprite.setSize(SCREEN_WIDTH, SCREEN_HEIGH);
    personSprite = new Sprite(personImage[0], _manager, X00, Y00 + 13, GameConstants.BOTTOM_HCENTER_ANCHOR);
    personSprite1 = new Sprite(personImage[0], _manager, X01, Y01 + 13, GameConstants.BOTTOM_HCENTER_ANCHOR);
    ngamSprite = new Sprite(ngamImage, _manager, xLine0[indexToado1] + ext[indexToado1], yLine[indexToado1] + extY[indexToado1], GameConstants.TOP_HCENTER_ANCHOR);

    ngamSprite.setDrawListener(new DrawListener() {
      public void paint(Sprite source, Graphics g) {
        if (!isDrawLine11 && !isDrawLine12) {
          ngamSprite.setImage(ngamImages[indexToado1]);
          ngamSprite.setAnchor(GameConstants.TOP_HCENTER_ANCHOR);
        }
      }
    });
    ngamSprite1 = new Sprite(ngamImage, _manager, xLine1[indexToado2] + ext[indexToado2], yLine[indexToado2] + extY[indexToado2], GameConstants.TOP_HCENTER_ANCHOR);

    ngamSprite1.setDrawListener(new DrawListener() {
      public void paint(Sprite source, Graphics g) {
        if (!isDrawLine21 && !isDrawLine22) {
          ngamSprite1.setImage(ngamImages[indexToado2]);
          ngamSprite1.setAnchor(GameConstants.TOP_HCENTER_ANCHOR);
        }
      }
    });
    
    groundSprite.setDrawListener(new DrawListener() {
      public void paint(Sprite source, Graphics g) {
        g.drawImage(bucdungImg, X00, Y00 + 18, GameConstants.BOTTOM_HCENTER_ANCHOR);
        g.drawImage(bucdungImg, X01, Y00 + 18, GameConstants.BOTTOM_HCENTER_ANCHOR);
        if (Constants.IS_240x320_SCREEN) {
          if (isMaster()) {
            g.drawImage(diem1Image, X01 - 80, 10, GameConstants.TOP_LEFT_ANCHOR);
            g.drawImage(diem2Image, X00 + 80, 10, GameConstants.TOP_RIGHT_ANCHOR);
          } else {
            g.drawImage(diem2Image, X01 - 80, 10, GameConstants.TOP_LEFT_ANCHOR);
            g.drawImage(diem1Image, X00 + 80, 10, GameConstants.TOP_RIGHT_ANCHOR);
          }
        } else {
          if (isMaster()) {
            g.drawImage(diem1Image, X00 - 110, 10, GameConstants.TOP_RIGHT_ANCHOR);
            g.drawImage(diem2Image, X01 + 110, 10, GameConstants.TOP_LEFT_ANCHOR);
          } else {
            g.drawImage(diem2Image, X00 - 110, 10, GameConstants.TOP_RIGHT_ANCHOR);
            g.drawImage(diem1Image, X01 + 110, 10, GameConstants.TOP_LEFT_ANCHOR);
          }
        }
        g.setColor(GameColor.BLACK_CODE);
        drawTNT1(g);
        drawTNT2(g);
        if (!isDrawLine11 && !isDrawLine12) {
          g.drawLine(X00, Y00, xLine0[indexToado1], yLine[indexToado1]);
        } else {
          g.drawLine(X00, Y00, (int) X, Y);
        }
        if (!isDrawLine21 && !isDrawLine22) {
          g.drawLine(X01, Y01, xLine1[indexToado2], yLine[indexToado2]);
        } else {
          g.drawLine(X01, Y01, (int) XX, YY);
        }
        scoreStr1 = String.valueOf(curentscore1);
        scoreStr2 = String.valueOf(curentscore2);
        timeStr = String.valueOf(time);
        if (Constants.IS_240x320_SCREEN) {
          for (int i = 0; i < scoreStr2.length(); i++) {
            String c = String.valueOf(scoreStr2.charAt(i));
            g.drawImage(bosoImage[NumberUtil.parseInt(c.trim()) + 1], 20 + i * 9, 40, GameConstants.TOP_LEFT_ANCHOR);
          }
          for (int j = 0; j < String.valueOf(scoreStr1).length(); j++) {
            String c = String.valueOf(scoreStr1.charAt(j));
            g.drawImage(bosoImage[NumberUtil.parseInt(c.trim()) + 1], 172 + j * 9, 41, GameConstants.TOP_LEFT_ANCHOR);
          }
          if (isMaster()) {
            text8.drawString2(g, "Level: " + myLevel, GameColor.BLACK_CODE, 195, 2, GameConstants.CENTER_ANCHOR);
            text8.drawString2(g, "Level: " + oppLevel, GameColor.BLACK_CODE, 45, 2, GameConstants.CENTER_ANCHOR);
            text8.drawString2(g, Global.currentUser.getName(), GameColor.BLACK_CODE, 180, 17, GameConstants.CENTER_ANCHOR);
            text8.drawString2(g, oponentName, GameColor.BLACK_CODE, 25, 17, GameConstants.CENTER_ANCHOR);
          } else {
            text8.drawString2(g, "Level: " + myLevel, GameColor.BLACK_CODE, 45, 2, GameConstants.CENTER_ANCHOR);
            text8.drawString2(g, "Level: " + oppLevel, GameColor.BLACK_CODE, 195, 2, GameConstants.CENTER_ANCHOR);
            text8.drawString2(g, Global.currentUser.getName(), GameColor.BLACK_CODE, 25, 17, GameConstants.CENTER_ANCHOR);
            text8.drawString2(g, oponentName, GameColor.BLACK_CODE, 185, 17, GameConstants.CENTER_ANCHOR);
          }
          if (isShowItemBoard) {
            g.drawImage(closeImage, 6, SCREEN_HEIGH - 20, GameConstants.TOP_LEFT_ANCHOR);
          }
        } else {
          for (int i = 0; i < scoreStr2.length(); i++) {
            String c = String.valueOf(scoreStr2.charAt(i));
            g.drawImage(bosoImage[NumberUtil.parseInt(c.trim()) + 1], 23 + i * 9, 41, GameConstants.TOP_LEFT_ANCHOR);
          }
          for (int j = 0; j < String.valueOf(scoreStr1).length(); j++) {
            String c = String.valueOf(scoreStr1.charAt(j));
            g.drawImage(bosoImage[NumberUtil.parseInt(c.trim()) + 1], 250 + j * 9, 41, GameConstants.TOP_LEFT_ANCHOR);
          }
          if (isMaster()) {
            text8.drawString2(g, "Level: " + myLevel, GameColor.BLACK_CODE, 270, 2, GameConstants.CENTER_ANCHOR);
            text8.drawString2(g, "Level: " + oppLevel, GameColor.BLACK_CODE, 46, 2, GameConstants.CENTER_ANCHOR);
            text8.drawString2(g, Global.currentUser.getName(), GameColor.BLACK_CODE, 255, 20, GameConstants.CENTER_ANCHOR);
            text8.drawString2(g, oponentName, GameColor.BLACK_CODE, 30, 20, GameConstants.CENTER_ANCHOR);
          } else {
            text8.drawString2(g, "Level: " + myLevel, GameColor.BLACK_CODE, 46, 2, GameConstants.CENTER_ANCHOR);
            text8.drawString2(g, "Level: " + oppLevel, GameColor.BLACK_CODE, 270, 2, GameConstants.CENTER_ANCHOR);
            text8.drawString2(g, Global.currentUser.getName(), GameColor.BLACK_CODE, 30, 20, GameConstants.CENTER_ANCHOR);
            text8.drawString2(g, oponentName, GameColor.BLACK_CODE, 255, 20, GameConstants.CENTER_ANCHOR);
          }
          if (isShowItemBoard) {
            g.drawImage(closeImage, 9, SCREEN_HEIGH - 20, GameConstants.TOP_LEFT_ANCHOR);
          }
        }
        g.drawImage(clockImage, SCREEN_WIDTH / 2 - 15, 17, GameConstants.TOP_LEFT_ANCHOR);
        for (int j = 0; j < String.valueOf(timeStr).length(); j++) {
          String c = String.valueOf(timeStr.charAt(j));
          g.drawImage(bosoImage[NumberUtil.parseInt(c.trim()) + 1], SCREEN_WIDTH / 2 + 3 + j * 9, 20, GameConstants.TOP_LEFT_ANCHOR);
        }
        if (isTangLuc1) {
          g.drawImage(boughtItem1, X00 + 40, Y00 + 15, GameConstants.BOTTOM_HCENTER_ANCHOR);
        }
        if (isRobber1) {
          g.drawImage(boughtItem2, X00 + 60, Y00 + 15, GameConstants.BOTTOM_HCENTER_ANCHOR);
        }
        if (isTangLuc2) {
          g.drawImage(boughtItem1, X01 - 40, Y01 + 15, GameConstants.BOTTOM_HCENTER_ANCHOR);
        }
        if (isRobber2) {
          g.drawImage(boughtItem2, X01 - 60, Y01 + 15, GameConstants.BOTTOM_HCENTER_ANCHOR);
        }
        // if (isShowItemBoard) {
        // g.drawImage(closeImage, 6, SCREEN_HEIGH - 20, GameConstants.TOP_LEFT_ANCHOR);
        // }
      }
    });
    for (int i = 0; i < countObject; i++) {
      objectSprite[i] = new Sprite(objectImages[i], _manager, ObjX[i], ObjY[i], Constants.TOP_LEFT_ANCHOR);
    }
    resultSprite = new Sprite(null, _manager, 0, 0, Constants.TOP_LEFT_ANCHOR);
    resultSprite.setSize(SCREEN_WIDTH, SCREEN_HEIGH);
    resultSprite.setDrawListener(new DrawListener() {
      public void paint(Sprite source, Graphics g) {
        if (isShowWinOrLostAlert) {
          g.drawImage(matnaImage, 0, 0, GameConstants.TOP_LEFT_ANCHOR);
          g.drawImage(starImage, SCREEN_WIDTH / 2, (SCREEN_HEIGH - 20) / 2, GameConstants.CENTER_ANCHOR);
          if (!isHoa) {
            if (winSide == getMySide()) {
              g.drawImage(thangImage, SCREEN_WIDTH / 2, (SCREEN_HEIGH - 20) / 2, GameConstants.CENTER_ANCHOR);
            } else {
              g.drawImage(thuaImage, SCREEN_WIDTH / 2, (SCREEN_HEIGH - 20) / 2, GameConstants.CENTER_ANCHOR);
            }
          } else {
            g.drawImage(hoaImage, SCREEN_WIDTH / 2, (SCREEN_HEIGH - 20) / 2, GameConstants.CENTER_ANCHOR);
          }
        }
        if (isShowResult) {
          isShowWinOrLostAlert = false;
          drawResult(g);
        }
      }
    });
    boardSprite = new Sprite(boardItemImg, _manager, 0, SCREEN_HEIGH - 20, Constants.BOTTOM_LEFT_ANCHOR);
    boardSprite.setVisible(isShowItemBoard);
    setTimerListener(this);
    GameGlobal.systemCanvas.setTimerDelay(80);
    DrawUtils.setBottomBar(_manager, "Mua đồ", "", "Thoát");
    isfinishInit = true;
    GameGlobal.systemCanvas.hideAlert();
  }

  public int getCountObject(String textFile) {
    String text = String.valueOf(DaoVangMap.DAO_VANG_MAP.get(textFile));
    StringArray lines = GameStringUtils.split(text, "\n");
    return NumberUtil.parseInt(lines.get(0));
  }

  public void alertEventPerform(int alertType, int eventType, int alertId) {
    if (alertId == 98) { // Sự kiện chính mình thoát ra giữa ván
      if (eventType == GameAlert.YES_BUTTON) {
        SocketClientUtil.leaveTableRequest();
        GameGlobal.nextState(FrmGroupListTableFreeUserChat.instance(), null);
      }
      return;
    } else if (alertId == 99) { // Sự kiện báo đối phương đã thoát hoặc time out
      winSide = getMySide();
      isShowWinOrLostAlert = true;
    }
  }

  public void draw(Graphics g) {
    g.drawImage(bgImage, 0, 0, GameConstants.TOP_LEFT_ANCHOR);
  }

  public void onConnectDone() {
  }

  public void onConnectFail() {
  }

  public void onDisconnect() {
    SocketClientUtil.leaveTableRequest();
    GameGlobal.nextState(FrmGroupListTableFreeUserChat.instance(), null);
  }

  public void onRecieveData(DataPackage dataPackage) {
    int header = dataPackage.getHeader();
    switch (header) {
    case START_TO_PLAY_RESPONSE:
      int lv = dataPackage.nextInt();
      time = dataPackage.nextInt();
      level = lv;
      oponentName = getOponentName();
      myLevel = getMyLevel();
      oppLevel = getOponentLevel();
      initForGame(dataPackage);
      break;
    case TIME_OUT_PER_QUESTION_SIGNAL:
      time--;
      break;
    case SELECT_TO_PULL:
      int message = dataPackage.nextInt();
      if (Global.currentUser.getName().equals(Global.currentTable.getTableMasterName())) {
        isDrawLine21 = true;
        selectIndex2 = message;
        XX = xLine1[selectIndex2];
        YY = yLine[selectIndex2];
        ngamSprite1.setImage(ngamImages[selectIndex2]);
        ngamSprite1.setAnchor(GameConstants.TOP_HCENTER_ANCHOR);
      } else {
        isDrawLine11 = true;
        selectIndex1 = message;
        X = xLine0[selectIndex1];
        Y = yLine[selectIndex1];
        ngamSprite.setImage(ngamImages[selectIndex1]);
        ngamSprite.setAnchor(GameConstants.TOP_HCENTER_ANCHOR);
      }
      break;
    case ROB_OBJECT:
      int idx = dataPackage.nextInt();
      if (isMaster()) {
        k2 = idx;
        isPulling1[k2] = false;
        isPulling2[k2] = true;
        isDrawLine21 = false;
        isDrawLine22 = true;
        isDrawLine12 = false;
        speed2 = getspeed2(idx);
        processAfterLostObject1();
      } else {
        k1 = idx;
        isPulling2[k1] = false;
        isPulling1[k1] = true;
        isDrawLine11 = false;
        isDrawLine12 = true;
        isDrawLine22 = false;
        speed1 = getspeed1(idx);
        processAfterLostObject2();
      }
      break;
    case SELECTED_ITEM:
      int selected_idx = dataPackage.nextInt();
      if (isMaster()) {
        k2 = selected_idx;
        isDrawLine21 = false;
        isDrawLine22 = true;
        isPulling2[k2] = true;
        speed2 = getspeed2(k2);
      } else {
        k1 = selected_idx;
        isDrawLine11 = false;
        isDrawLine12 = true;
        isPulling1[k1] = true;
        speed1 = getspeed1(k1);
      }
      break;
    case BUY_ITEM:
      int cate = dataPackage.nextInt();
      if (isMaster()) {
        if (cate == 1) {
          isTangLuc2 = true;
        } else if (cate == 2) {
          isRobber2 = true;
        }
      } else {
        if (cate == 1) {
          isTangLuc1 = true;
        } else {
          isRobber1 = true;
        }
      }
      break;
    case SUCCESS_PULL:
      curentscore1 = dataPackage.nextInt();
      curentscore2 = dataPackage.nextInt();
      break;
    case WIN_GAME_NOTIFY_RESPONSE:
      isEndGame = true;
      isShowItemBoard = false;
      // boardSprite.setVisible(isShowItemBoard);
      winSide = dataPackage.nextInt();

      isShowWinOrLostAlert = true;
      int reason = dataPackage.nextInt();
      moneyChangePoint[0] = String.valueOf(dataPackage.nextInt());
      moneyChangePoint[1] = String.valueOf(dataPackage.nextInt());
      if (reason == OPPONENT_RESIGN_WIN_REASON) {
        if (winSide == getMySide()) {
          GameGlobal.alert.showAlert1(this, GameAlert.OK_TYPE, StringArray.create1( "Đối thủ đã bỏ cuộc", "Bạn đã thắng" ), 99);
        }
        // if (isShowResult || isShowWinOrLostAlert) {
        // GameGlobal.alert.showAlert(this, Alert.OK_TYPE, new String[]{"Đối thủ đã thoát"}, 100);
        // } else {
        // GameGlobal.alert.showAlert(this, Alert.YES_NO_TYPE, new String[]{"Đối thủ đã thoát", "Bạn đã thắng!"}, 99);
        // }

      } else if (reason == EQUAL_GAME_RESULT) {
        isHoa = true;
      } else if (reason == NORMAL_WIN_REASON) {
      }
      break;
    }
  }

  public void drawResult(Graphics g) {
    if (GameConstants.IS_240x320_SCREEN) {
      DrawUtils.drawHozPopup(g, 183, 23, 82);
      text8.drawString2(g, "KẾT QUẢ", GameColor.WHITE_CODE, SCREEN_WIDTH / 2, 104, GameConstants.TOP_HCENTER_ANCHOR);
      g.setColor(GameColor.RED2_CODE);
      g.drawLine(35, 121, 205, 121);
      if (!isHoa) {
        text8.drawString2(g, "Thắng:", GameColor.WHITE_CODE, 43, 129, GameConstants.TOP_LEFT_ANCHOR);
        text8.drawString2(g, "Thua:", GameColor.WHITE_CODE, 43, 147, GameConstants.TOP_LEFT_ANCHOR);
      } else {
        text8.drawString2(g, "Hòa:", GameColor.WHITE_CODE, 43, 129, GameConstants.TOP_LEFT_ANCHOR);
        text8.drawString2(g, "Hòa:", GameColor.WHITE_CODE, 43, 147, GameConstants.TOP_LEFT_ANCHOR);
      }

      if (winSide == getMySide()) {
        text8.drawString2(g, Global.currentUser.getName(), GameColor.WHITE_CODE, 88, 129, GameConstants.TOP_LEFT_ANCHOR);
        text8.drawString2(g, oponentName, GameColor.WHITE_CODE, 88, 147, GameConstants.TOP_LEFT_ANCHOR);
      } else {
        text8.drawString2(g, oponentName, GameColor.WHITE_CODE, 88, 129, GameConstants.TOP_LEFT_ANCHOR);
        text8.drawString2(g, Global.currentUser.getName(), GameColor.WHITE_CODE, 88, 147, GameConstants.TOP_LEFT_ANCHOR);
      }
      text8.drawString2(g, moneyChangePoint[0] + " gold", GameColor.WHITE_CODE, 161, 129, GameConstants.TOP_LEFT_ANCHOR);
      text8.drawString2(g, moneyChangePoint[1] + " gold", GameColor.WHITE_CODE, 161, 147, GameConstants.TOP_LEFT_ANCHOR);
    } else {
      DrawUtils.drawHozPopup(g, 183, 68, 82);
      text8.drawString2(g, "KẾT QUẢ", GameColor.WHITE_CODE, SCREEN_WIDTH / 2, 104, GameConstants.TOP_HCENTER_ANCHOR);
      g.setColor(GameColor.RED2_CODE);
      g.drawLine(75, 121, 205, 121);
      if (!isHoa) {
        text8.drawString2(g, "Thắng:", GameColor.WHITE_CODE, 83, 129, GameConstants.TOP_LEFT_ANCHOR);
        text8.drawString2(g, "Thua:", GameColor.WHITE_CODE, 83, 147, GameConstants.TOP_LEFT_ANCHOR);
      } else {
        text8.drawString2(g, "Hòa:", GameColor.WHITE_CODE, 83, 129, GameConstants.TOP_LEFT_ANCHOR);
        text8.drawString2(g, "Hòa:", GameColor.WHITE_CODE, 83, 147, GameConstants.TOP_LEFT_ANCHOR);
      }

      if (winSide == getMySide()) {
        text8.drawString2(g, Global.currentUser.getName(), GameColor.WHITE_CODE, 128, 129, GameConstants.TOP_LEFT_ANCHOR);
        text8.drawString2(g, oponentName, GameColor.WHITE_CODE, 128, 147, GameConstants.TOP_LEFT_ANCHOR);
      } else {
        text8.drawString2(g, oponentName, GameColor.WHITE_CODE, 128, 129, GameConstants.TOP_LEFT_ANCHOR);
        text8.drawString2(g, Global.currentUser.getName(), GameColor.WHITE_CODE, 128, 147, GameConstants.TOP_LEFT_ANCHOR);
      }
      text8.drawString2(g, moneyChangePoint[0] + " gold", GameColor.WHITE_CODE, 201, 129, GameConstants.TOP_LEFT_ANCHOR);
      text8.drawString2(g, moneyChangePoint[1] + " gold", GameColor.WHITE_CODE, 201, 147, GameConstants.TOP_LEFT_ANCHOR);
    }
    DrawUtils.getBottomBar(_manager).setCenterLabel("Chơi tiếp");
    // g.drawImage(continueImage, SCREEN_WIDTH/2, SCREEN_HEIGH - 20, GameConstants.TOP_HCENTER_ANCHOR);
  }

  public String getOponentName() {
    User user = ((User) Global.tableUsers.elementAt(0));

    if (user.getName().compareTo(Global.currentUser.getName()) == 0) {
      String name = ((User) Global.tableUsers.elementAt(1)).getName();
      return name;
    } else {
      return user.getName();
    }
  }

  public int getOponentLevel() {
    User user = ((User) Global.tableUsers.elementAt(0));
    if (user.getName().compareTo(Global.currentUser.getName()) == 0) {
      int name = ((User) Global.tableUsers.elementAt(1)).getLevel();
      return name;
    } else {
      return user.getLevel();
    }
  }

  public int getMyLevel() {
    User user = ((User) Global.tableUsers.elementAt(0));
    if (user.getName().compareTo(Global.currentUser.getName()) == 0) {
      int name = ((User) Global.tableUsers.elementAt(1)).getLevel();
      return name;
    } else {
      return user.getLevel();
    }
  }

  public int getMySide() {
    if (isMaster()) {
      return 0;
    } else {
      return 1;
    }
  }

  public int getOponentSide() {
    if (getMySide() == 0) {
      return 1;
    } else {
      return 0;
    }
  }

  public void drawTNT1(Graphics g) {
    if (isTNT1) {
      for (int i = 0; i < countObject; i++) {
        if (Math.abs(objectSprite[i].getRealX() - objectSprite[k1].getRealX()) < 50 && Math.abs(objectSprite[i].getRealY() - objectSprite[k1].getRealY()) < 50) {
          objectSprite[i].setVisible(false);
        }
      }
      objectSprite[k1].setVisible(false);
      count = count + 1;
      if (count < 50) {
        if (count % 5 == 0) {
          g.drawImage(noImgs[count % 7], objectSprite[k1].getRealX(), objectSprite[k1].getRealY(), GameConstants.CENTER_ANCHOR);
        }
      } else {
        isTNT1 = false;
      }
    }
  }

  public void drawTNT2(Graphics g) {
    if (isTNT2) {
      for (int i = 0; i < countObject; i++) {
        if (Math.abs(objectSprite[i].getRealX() - objectSprite[k2].getRealX()) < 50 && Math.abs(objectSprite[i].getRealY() - objectSprite[k2].getRealY()) < 50) {
          objectSprite[i].setVisible(false);
        }
      }
      objectSprite[k2].setVisible(false);

      count = count + 1;
      if (count < 50) {
        if (count % 5 == 0) {
          g.drawImage(noImgs[count % 7], objectSprite[k2].getRealX(), objectSprite[k2].getRealY(), GameConstants.CENTER_ANCHOR);
        }
      } else {
        isTNT2 = false;
      }
    }
  }

  private boolean isMaster() {
    if (Global.currentUser.getName().equals(Global.currentTable.getTableMasterName())) {
      return true;
    } else {
      return false;
    }
  }

  private void sendResultToServer(int header, int sc1, int sc2) {
    DataPackage dataPackage = Game.createGamePackage(header);
    dataPackage.putInt(sc1);
    dataPackage.putInt(sc2);
    Global.gameActionClient.write(dataPackage);
  }

  private void sendMessageToserver(int header, int x) {
    DataPackage dataPackage = Game.createGamePackage(header);
    dataPackage.putInt(x);
    Global.gameActionClient.write(dataPackage);
  }

  public void keyReleased(int keyCode) {
    if (!isfinishInit) {
      return;
    }
    switch (keyCode) {
    case Key.DOWN:
      if (!isShowWinOrLostAlert) {
        if (Global.currentUser.getName().equals(Global.currentTable.getTableMasterName())) {
          if (!isEndgame) {
            if (!isDrawLine12 && !isDrawLine11) {
              sendMessageToserver(SELECT_TO_PULL, indexToado1);
              isDrawLine11 = true;
              selectIndex1 = indexToado1;
              X = xLine0[selectIndex1];
              Y = yLine[selectIndex1];
            }
          }
        } else {
          if (!isEndgame) {
            if (!isDrawLine22 && !isDrawLine21) {
              sendMessageToserver(SELECT_TO_PULL, indexToado2);
              isDrawLine21 = true;
              selectIndex2 = indexToado2;
              XX = xLine1[selectIndex2];
              YY = yLine[selectIndex2];
            }
          }
        }
      }
      break;
    case Key.FIRE:
      if (isShowResult) {
        GameGlobal.nextState(FrmGroupTableFreeUserFriend.instance(), null);
        return;
      }
      if (isShowWinOrLostAlert) {
        isShowWinOrLostAlert = false;
        isShowResult = true;
      }

      break;
    case Key.SOFT_LEFT:
      if (!isShowResult && !isShowWinOrLostAlert) {
        isShowItemBoard = !isShowItemBoard;
        boardSprite.setVisible(isShowItemBoard);
      }
      break;
    case Key.SOFT_RIGHT:
      if (!isShowResult && !isShowWinOrLostAlert) {
        GameGlobal.alert.showAlert1(this, GameAlert.YES_NO_TYPE, StringArray.create1( "Thoát ra bị tính là thua cuộc", "Bạn có muốn thoát ra?" ), 98);
      } else {
        SocketClientUtil.leaveTableRequest();
        GameGlobal.nextState(FrmGroupListTableFreeUserChat.instance(), null);
      }
      break;
    case Key.UP:
      break;
    case Key.STAR:
      if (!isShowResult && !isShowWinOrLostAlert) {
        if (isMaster()) {
          isTangLuc1 = true;
          sendResultToServer(BUY_ITEM, 1, 1);
        } else {
          isTangLuc2 = true;
          sendResultToServer(BUY_ITEM, 1, 2);
        }
      }
      break;
    case Key.POUND:
      if (!isShowResult && !isShowWinOrLostAlert) {
        if (isMaster()) {
          isRobber1 = true;
          sendResultToServer(BUY_ITEM, 2, 1);
        } else {
          isRobber2 = true;
          sendResultToServer(BUY_ITEM, 2, 2);
        }
      }
      break;
    default:
      break;
    }
  }

  public String[] readMapText(String textFile, int[] x, int[] y) {
    String text = String.valueOf(DaoVangMap.DAO_VANG_MAP.get(textFile));
    StringArray lines = GameStringUtils.split(text, "\n");
    int numberOfResource = NumberUtil.parseInt(lines.get(0));
    String[] name = new String[numberOfResource];
    for (int i = 1; i < lines.len() - 1; i++) {
      StringArray tmp = GameStringUtils.split(lines.get(i), " ");
      name[i - 1] = tmp.get(0).trim();
      
      StringArray tmp1 = GameStringUtils.split(tmp.get(1), ",");
      x[i - 1] = NumberUtil.parseInt(tmp1.get(0).trim());
      y[i - 1] = NumberUtil.parseInt(tmp1.get(1).trim());
      if (!Constants.IS_240x320_SCREEN) {
        x[i - 1] += 40; // đồng hóa tọa độ bản dọc với bản ngang
        y[i - 1] -= 40;
      }
    }
    return name;
  }

  public void destroy() {
    groundSprite = null;
    ngamSprite = null;
    ngamSprite1 = null;
    personSprite = null;
    personSprite1 = null;
    objectSprite = null;
    personImage = null;
    ngamImages = null;
    ngamImage = null;
    objectImages = null;
    personLargeImg = null;
    bgImage = null;
    ObjX = null;
    ObjY = null;
    xLine0 = null;
    xLine1 = null;
    yLine = null;
    nameObject = null;
    randString2 = null;
    rd = null;
    bosoImg = null;
    bosoImage = null;
    scoreStr1 = null;
    timeStr = null;
    dxMouse = null;
    noImgs = null;
    bucdungImg = null;
    ext = null;
    extY = null;
    TRIANGLE = null;
    cosin = null;
    isPulling1 = null;
    isPulling2 = null;
    diem1Image = null;
    diem2Image = null;
    text8 = null;
    scoreStr2 = null;
    matnaImage = null;
    randManaImage = null;
    starImage = null;
    thangImage = null;
    thuaImage = null;
    boughtItem1 = null;
    boardItemImg = null;
    scoreStr2 = null;
    boughtItem2 = null;
    resultSprite = null;
    clockImage = null;
    hoaImage = null;
    boardSprite = null;
    oponentName = null;
    // continueImage = null;
    closeImage = null;
    boughtItem2 = null;
  }

  public void doTask() {
    if (isEndGame) {
      return;
    }

    step = (step + 1) % 3000;
    if (checkChuot()) {
      xuLiDoituongChuot();
    }
    /*
     * if (step % 20 == 0 && time > 0) { time -= 1; }
     */
    if (time <= 0 || isHaveNoItem()) {
      isDrawLine11 = false;
      isDrawLine12 = false;
      isDrawLine21 = false;
      isDrawLine22 = false;

      if (isMaster()) {
        if (!sent) {
          sendResultToServer(END_GAME, curentscore1, curentscore2);
          sent = true;
        }
      } else {
        // isHoa = true;
      }
      return;
    } else {
      forngamSprite1();
      forngamSprite2();
    }
  }

  public boolean isHaveNoItem() {
    for (int i = 0; i < countObject; i++) {
      if (objectSprite[i].isVisible()) {
        return false;
      }
    }
    return true;
  }

  public void forngamSprite1() {
    if (isDrawLine11) {
      if (X < DX || X > SCREEN_WIDTH - DX || Y > SCREEN_HEIGH - 30) {
        isDrawLine11 = false;
      }
      if (selectIndex1 == 14) {
        Y += 4;
      } else if (selectIndex1 < 14) {
        Y += 4 * cosin[selectIndex1];
        X = (X00 - (Y - Y00) * this.TRIANGLE[selectIndex1]);
      } else {
        Y += 4 * cosin[(27 - selectIndex1)];
        X = (X00 + (Y - Y00) * this.TRIANGLE[(27 - selectIndex1)]);
      }
      ngamSprite.setPosition((int) X + ext[indexToado1], Y + extY[indexToado1]);
      if (isMaster()) {
        speed1 = processAfterCollides1();
      }
    }

    if (isDrawLine12) {

      if (step % (8 / speed1) == 0) {
        if (selectIndex1 == 14) {
          Y -= speed1;
        } else if (selectIndex1 < 14) {
          Y -= speed1 * cosin[selectIndex1];
          X = (X00 - (Y - Y00) * TRIANGLE[selectIndex1]);
        } else {
          Y -= speed1 * cosin[27 - selectIndex1];
          X = (X00 + (Y - Y00) * TRIANGLE[(27 - selectIndex1)]);
        }
      }

      personSprite.setImage(personImage[step % 5]);
      personSprite.setAnchor(GameConstants.BOTTOM_HCENTER_ANCHOR);
      ngamSprite.setPosition((int) X + ext[indexToado1], Y + extY[indexToado1]);
      if (!nameObject[k1].equals("tnt")) {
        objectSprite[k1].setPosition((int) (X - objectImages[k1].getWidth() / 2 + ext[indexToado1]), Y + extY[indexToado1]);
      }
      if (ngamSprite.checkCollides1(personSprite)) {
        processAfterPull();
        if (isMaster()) {
          sendResultToServer(SUCCESS_PULL, 0, costObject(k1));
        }

      }
    }

    if (!isDrawLine11 && !isDrawLine12) {
      indexToado1 += dx1;
      if (indexToado1 == 0 || indexToado1 == 26) {
        dx1 = -dx1;
      }
      ngamSprite.setPosition(xLine0[indexToado1] + ext[indexToado1], yLine[indexToado1] + extY[indexToado1] - 4);

    }
  }

  public void forngamSprite2() {
    if (isDrawLine21) {
      if (XX < DX || XX > SCREEN_WIDTH - DX || YY > SCREEN_HEIGH - 30) {
        isDrawLine21 = false;
      }
      if (selectIndex2 == 14) {
        YY += 4;
      } else if (selectIndex2 < 14) {
        YY += 4 * cosin[selectIndex2];
        XX = (X01 - (YY - Y01) * this.TRIANGLE[selectIndex2]);
      } else {
        YY += 4 * cosin[(27 - selectIndex2)];
        XX = (X01 + (YY - Y01) * this.TRIANGLE[(27 - selectIndex2)]);
      }
      ngamSprite1.setPosition((int) XX + ext[indexToado2], YY + extY[indexToado2]);
      if (!isMaster()) {
        speed2 = processAfterCollides2();
      }

    }

    if (isDrawLine22) {

      if (step % (8 / speed2) == 0) {
        if (selectIndex2 == 14) {
          YY -= speed2;
        } else if (selectIndex2 < 14) {
          YY -= speed2 * cosin[selectIndex2];
          XX = (X01 - (YY - Y01) * TRIANGLE[selectIndex2]);
        } else {
          YY -= speed2 * cosin[27 - selectIndex2];
          XX = (X01 + (YY - Y01) * TRIANGLE[(27 - selectIndex2)]);
        }
      }

      personSprite1.setImage(personImage[step % 5]);
      personSprite1.setAnchor(GameConstants.BOTTOM_HCENTER_ANCHOR);
      ngamSprite1.setPosition((int) XX + ext[indexToado2], YY + extY[indexToado2]);
      objectSprite[k2].setPosition((int) (XX - objectImages[k2].getWidth() / 2 + ext[indexToado2]), YY + extY[indexToado2]);
      if (ngamSprite1.checkCollides1(personSprite1)) {
        processAfterPull1();
        if (!isMaster()) {
          sendResultToServer(SUCCESS_PULL, 1, costObject(k2));
        }
      }
    }

    if (!isDrawLine21 && !isDrawLine22) {
      indexToado2 += dx2;
      if (indexToado2 == 0 || indexToado2 == 26) {
        dx2 = -dx2;
      }
      ngamSprite1.setPosition(xLine1[indexToado2] + ext[indexToado2], yLine[indexToado2] + extY[indexToado2] - 4);
    }
  }

  public int processAfterCollides1() {
    int speed = 8;
    for (int i = 0; i < countObject; i++) {
      // if (ngamSprite.checkCollides(objectSprite[i])) {
      if (objectSprite[i].checkCollidesWithRect(ngamSprite.getRealX() + 6, ngamSprite.getRealY(), ngamSprite.getWidth() - 12, ngamSprite.getHeight() - 4)) {
        k1 = i;
        if (!isPulling2[i]) {
          sendMessageToserver(SELECTED_ITEM, i);
          isPulling1[i] = true;
          isDrawLine11 = false;
          isDrawLine12 = true;
          speed = getspeed1(i);
        } else {
          if (isRobber1) {
            speed = getspeed1(i);
            processAfterRobbed2();
            isPulling2[i] = false;
            isPulling1[i] = true;
            isDrawLine11 = false;
            isDrawLine12 = true;
            isDrawLine22 = false;
            sendMessageToserver(ROB_OBJECT, i);
          }
        }
      }
    }
    return speed;
  }

  private int calculateSpeadObject(int ObjectIndex, int userIndex) {
    int speed = 8;
    if (nameObject[ObjectIndex].equals("tnt")) {
      if (userIndex == 0) {
        isTNT1 = true;
        isDrawLine12 = false;
        processAfterPull();
      } else {
        isTNT2 = true;
        isDrawLine22 = false;
        processAfterPull1();
      }
    } else {
      if (nameObject[ObjectIndex].compareTo("vangto") == 0 || nameObject[ObjectIndex].compareTo("dato") == 0) {
        speed = 2;
      } else if (nameObject[ObjectIndex].compareTo("vangvua") == 0 || nameObject[ObjectIndex].compareTo("da") == 0) {
        speed = 4;
      } else if (nameObject[ObjectIndex].compareTo("vangnho") == 0 || nameObject[ObjectIndex].compareTo("goiqua") == 0 || nameObject[ObjectIndex].compareTo("kimcuong") == 0
          || nameObject[ObjectIndex].compareTo("chuotKC") == 0 || nameObject[ObjectIndex].compareTo("chuot") == 0) {
        speed = 8;
      } else if (nameObject[ObjectIndex].compareTo("xuong") == 0) {
        speed = 8;
      } else {
        speed = 8;
      }
    }
    return speed;
  }

  private int getspeed1(int ObjectIndex) {
    int speed = 8;
    speed = calculateSpeadObject(ObjectIndex, 0);
    if (isTangLuc1) {
      speed = 8;
    }
    return speed;
  }

  private int getspeed2(int ObjectIndex) {
    int speed = 8;
    speed = calculateSpeadObject(ObjectIndex, 1);
    if (isTangLuc2) {
      speed = 8;
    }
    return speed;
  }

  public int processAfterCollides2() {
    int speed = 8;
    for (int i = 0; i < countObject; i++) {
      if (objectSprite[i].checkCollidesWithRect(ngamSprite1.getRealX() + 6, ngamSprite1.getRealY(), ngamSprite1.getWidth() - 12, ngamSprite1.getHeight() - 4)) {
        // if (ngamSprite1.checkCollides(objectSprite[i])) {
        k2 = i;
        if (!isPulling1[i]) {
          sendMessageToserver(SELECTED_ITEM, i);
          isPulling2[i] = true;
          isDrawLine21 = false;
          isDrawLine22 = true;
          speed = getspeed2(i);
        } else {
          if (isRobber2 /* && !isLostObject2 */) {
            speed = getspeed2(i);
            processAfterRobbed1();
            isPulling1[i] = false;
            isPulling2[i] = true;
            isDrawLine21 = false;
            isDrawLine22 = true;
            sendMessageToserver(ROB_OBJECT, i);
          }
        }
      }
    }
    return speed;
  }

  public void processAfterPull() {
    // curentscore1 += costObject(k1);
    isDrawLine12 = false;
    count = 0;
    objectSprite[k1].setVisible(false);
    ngamSprite.setPosition(xLine0[indexToado1] + ext[indexToado1], yLine[indexToado1] + extY[indexToado1]);
  }

  public void processAfterRobbed1() {
    isDrawLine12 = false;
    count = 0;
    ngamSprite.setPosition(xLine0[indexToado1] + ext[indexToado1], yLine[indexToado1] + extY[indexToado1]);
  }

  public void processAfterLostObject1() {
    isDrawLine12 = false;
    count = 0;
    ngamSprite.setPosition(xLine0[indexToado1] + ext[indexToado1], yLine[indexToado1] + extY[indexToado1]);
  }

  public void processAfterPull1() {
    // curentscore2 += costObject(k2);
    isDrawLine22 = false;
    count = 0;
    objectSprite[k2].setVisible(false);
    ngamSprite1.setPosition(xLine1[indexToado2] + ext[indexToado2], yLine[indexToado2] + extY[indexToado2]);
  }

  public void processAfterRobbed2() {
    isDrawLine22 = false;
    count = 0;
    ngamSprite1.setPosition(xLine1[indexToado2] + ext[indexToado2], yLine[indexToado2] + extY[indexToado2]);
  }

  public void processAfterLostObject2() {
    isDrawLine22 = false;
    count = 0;
    ngamSprite1.setPosition(xLine1[indexToado2] + ext[indexToado2], yLine[indexToado2] + extY[indexToado2]);
  }

  public int costObject(int k) {
    int cost = 0;
    if (nameObject[k].compareTo("vangto") == 0) {
      cost = 500;
    }
    if (nameObject[k].compareTo("vangvua") == 0) {
      cost = 200;
    }
    if (nameObject[k].compareTo("vangnho") == 0) {
      cost = 100;
    }
    if (nameObject[k].compareTo("dato") == 0) {
      cost = 50;
    }
    if (nameObject[k].compareTo("da") == 0) {
      cost = 30;
    }
    if (nameObject[k].compareTo("kimcuong") == 0) {
      cost = 650;
    }
    if (nameObject[k].compareTo("xuong") == 0) {
      cost = 2;
    }
    if (nameObject[k].compareTo("daulau") == 0) {
      cost = 5;
    }
    if (nameObject[k].compareTo("chuot") == 0) {
      cost = 4;
    }
    if (nameObject[k].compareTo("chuotKC") == 0) {
      cost = 800;
    }
    if (nameObject[k].compareTo("goiqua") == 0) {
      int tmp = rd.nextInt(10);
      cost = NumberUtil.parseInt(randString2[tmp].trim());
    }
    if ((nameObject[k].compareTo("xuong") == 0) || (nameObject[k].compareTo("daulau")) == 0 || (nameObject[k].compareTo("tnt")) == 0) {
      cost = 2;
    }
    return cost;
  }

  public boolean checkChuot() {
    boolean check = false;
    for (int i = 0; i < countObject; i++) {
      if (nameObject[i].compareTo("chuot") == 0 || nameObject[i].compareTo("chuotKC") == 0) {
        check = true;
      }
    }
    return check;
  }

  public void xuLiDoituongChuot() {
    for (int i = 0; i < countObject; i++) {
      if (nameObject[i].compareTo("chuot") == 0 || nameObject[i].compareTo("chuotKC") == 0) {
        if (i != k1 && i != k2 && i < countObject - 1) {
          if (objectSprite[i].getRealX() >= SCREEN_WIDTH - DX) {
            dxMouse[i] = dxMouse[i] * (-1);
            objectSprite[i].setImage(objectImages[i]);
            objectSprite[i].setAnchor(GameConstants.TOP_LEFT_ANCHOR);
          }
          if (objectSprite[i].getRealX() <= DX) {
            dxMouse[i] = dxMouse[i] * (-1);
            objectSprite[i].setImage(ImageUtil.transformMirror(objectImages[i]));
            objectSprite[i].setAnchor(GameConstants.TOP_LEFT_ANCHOR);
          }
          objectSprite[i].move(dxMouse[i], 0);
        }
      }
    }
  }
}
